package com.stars.distributed.schedule.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Hash算法工具类
 *
 * @author guoguifang
 */
public class HashUtil {

    private static final char[] DIGESTS_LOWER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 获取sha1值
     */
    public static String sha1(String data) {
        try {
            byte[] digest = MessageDigest.getInstance("SHA-1").digest(data.getBytes("UTF-8"));
            int l = digest.length;
            char[] out = new char[l << 1];
            int i = 0;
            for (int j = 0; i < l; ++i) {
                out[j++] = DIGESTS_LOWER[(240 & digest[i]) >>> 4];
                out[j++] = DIGESTS_LOWER[15 & digest[i]];
            }
            return new String(out);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取md5值
     */
    public static String md5(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] inputByteArray = data.getBytes("UTF-8");
            messageDigest.update(inputByteArray);
            byte[] byteArray = messageDigest.digest();
            char[] out = new char[byteArray.length * 2];
            int index = 0;
            for (byte b : byteArray) {
                out[index++] = DIGESTS_LOWER[b >>> 4 & 0xf];
                out[index++] = DIGESTS_LOWER[b & 0xf];
            }
            return new String(out);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

}
